<template>
	<mescroll-uni ref="mescrollRef" top="80rpx" @init="mescrollInit" @down="downCallback" @up="upCallback"
		:down="downOption" :up="upOption">
		<view class="order-list">
			<view v-for="(item, index) in orderList" :key="index" class="order-item bg-white m-t-20">
				<view class="order-con">
					<template v-if="orderType == 'aftersales'">
						<view class="sale-header flex row-between">
							<view style="height: 80rpx;flex: 1;">
								<shop-title :shop="{name: item.shop_name, id: item.sid}"></shop-title>
							</view>
							<view class="primary flex-none m-l-20">{{item.after_sale.type_text}}</view>
						</view>
						<view v-for="(cell, index2) in item.order_goods" :key="index2">
							<router-link :to="{path: '/bundle/pages/after_sales_detail/after_sales_detail',
								query: { id: item.after_sale.after_sale_id,}}">
								<view class="sale-content">
									<view class="flex">
										<view class="goods-img">
											<u-image width="160rpx" height="160rpx" border-radius="6rpx" :src="cell.image" />
										</view>
										<view class="goods-desc m-l-24">
											<view class="goods-name line-2">{{cell.goods_name}}</view>
											<view class="m-t-10 xs line-1 muted">{{cell.spec_value_str}}</view>
											<view class="flex row-between m-t-20">
												<price-format class="sm" :first-size="30" :second-size="30" :subscript-size="26"
													:price="cell.goods_price" />
												<view>x{{cell.goods_num}}</view>
											</view>
										</view>
									</view>
									<view class="sale-status m-t-20 flex">
										<view class="bold">申请状态</view>
										<view class="m-l-20">{{item.after_sale.desc}}</view>
									</view>
								</view>
							</router-link>
							<view class="sale-footer flex row-right">
								<view class="row-center flex br16 m-r-20 btn black-btn"
									@tap="onShowDialog(item.after_sale.after_sale_id)">
									撤销申请
								</view>
								<router-link :to="{path: '/bundle/pages/apply_refund/apply_refund',
										query: { 
										after_sale_id: item.after_sale.after_sale_id, 
										order_id: item.order_id,
										item_id: cell.item_id}}" v-if="item.after_sale.status == 4 || item.after_sale.status == 1">
									<view class="row-center flex br16 m-r-20 btn primary">重新申请</view>
								</router-link>
								<router-link :to="{path: '/bundle/pages/after_sales_detail/after_sales_detail',
								query: { id: item.after_sale.after_sale_id,}}" v-if="item.after_sale.status == 2">
									<view class="row-center flex br16 m-r-20 btn black-btn">
										查看详情
									</view>
								</router-link>
							</view>
						</view>
					</template>
					<router-link v-else :to="{
							  path: '/bundle/pages/order_details/order_details',
							  query: { id: item.id },
							}">
						<order-goods :list="item.order_goods" :isJumpGoods="false"></order-goods>
					</router-link>
					<view class="pickup-box" v-if="item.delivery_type==3">
						<view :class="item.order_status == 4 ? 'muted' : 'primary'" style="flex: 1;font-weight: 700;">
							自提门店地址</view>
						<view class="pickup-info">
							<text class="pickup-short sm lighter">{{item.shop.shop_address}}</text>
							<image src="../../static/images/icon_map.png"
								style="width: 48rpx;height: 48rpx;border-radius: 50%;" @click="showMapApp(item.shop)">
							</image>
						</view>
						<view class="pickup-code">
							取货码：<text>{{item.pickupCodeShow?item.pickup_code:'******'}}</text><text class="text-blue"
								style="margin-left: 40rpx;font-weight: 500;"
								@click="codeShowChange(item)">{{item.pickupCodeShow?'隐藏':'显示'}}</text>
						</view>
					</view>
					<view class="all-price flex">
						<view :class="item.order_status == 4 ? 'muted' : 'primary'" style="flex: 1;font-weight: 700;">
							<!-- 							<template v-if="item.delivery_type != 2">
								{{ getOrderStatus(item.order_status_desc) }}
							</template> -->
							<template v-if="orderType != 'aftersales'">
								{{ item.order_status_desc }}
							</template>
						</view>
						<text class="muted xxs">共{{ handlegoodCount(item) }}件商品，合计：</text>
						<price-format weight="700" :subscript-size="18" :first-size="28" :second-size="28"
							:price="item.order_amount" color="#fa7b63"></price-format>
					</view>
				</view>
				<view class="order-footer flex" v-if="
              item.cancel_btn ||
              item.delivery_btn ||
              item.take_btn ||
              item.del_btn ||
              item.pay_btn ||
              item.comment_btn ||
              item.pickup_btn
            ">
					<view style="flex: 1">
						<view class="primary flex sm" v-if="getCancelTime(item.order_cancel_time) > 0">
							<u-count-down separator="zh" :timestamp="getCancelTime(item.order_cancel_time)"
								:separator-color="colorConfig.primary" :color="colorConfig.primary" :separator-size="26"
								:font-size="26" bg-color="transparent" @end="refresh"></u-count-down>
						</view>
					</view>
					<view v-if="item.cancel_btn">
						<button size="sm" class="plain br16 lighter" hover-class="none"
							@tap.stop="cancelOrder(item.id)">
							取消订单
						</button>
					</view>
					<view v-if="item.delivery_btn" @tap.stop="">
						<router-link :to="{
                  path: '/bundle/pages/goods_logistics/goods_logistics',
                  query: { id: item.id },
                }">
							<button size="sm" class="btn plain br16 lighter" hover-class="none">
								查看物流
							</button>
						</router-link>
					</view>
					<view v-if="item.content_btn" @tap.stop="" class="m-l-20">
						<router-link :to="{
                  path: '/bundle/pages/order_details/order_details',
                  query: { id: item.id },
                }">
							<button size="sm" class="btn plain br16 lighter" hover-class="none">
								查看内容
							</button>
						</router-link>
					</view>
					<view v-if="item.pickup_btn" @tap.stop="" class="m-l-20">
						<router-link :to="{
                  path: '/bundle/pages/order_details/order_details',
                  query: { id: item.id },
                }">
							<button size="sm" class="btn bg-primary plain br16 white" style="border: none"
								hover-class="none">
								查看取货码
							</button>
						</router-link>
					</view>
					<view v-if="item.del_btn">
						<button size="sm" class="btn plain br16 lighter" hover-class="none"
							@tap.stop="delOrder(item.id)">
							删除订单
						</button>
					</view>
					<view v-if="item.pay_btn" class="m-l-20">
						<button size="sm" class="btn bg-primary br16 white" @tap.stop="payNow(item.id)">
							立即付款
						</button>
					</view>
					<!-- 					<view v-if="item.comment_btn" class="m-l-20">
						<button size="sm" hover-class="none" class="btn plain btn br16 primary red">
							去评价
						</button>
					</view> -->
					<view v-if="item.take_btn" class="m-l-20">
						<button size="sm" class="btn plain br16 primary red" hover-class="none"
							@tap.stop="comfirmOrder(item.id)">
							确认收货
						</button>
					</view>
				</view>
			</view>
		</view>
		<order-dialog ref="orderDialog" :order-id="orderId" :type="type" @confirm="confirmDialog"></order-dialog>
		<loading-view v-if="showLoading" background-color="transparent" :size="50"></loading-view>
		<u-modal v-model="showDialog" confirm-text="确定" :showCancelButton="true" :confirm-color="colorConfig.primary"
			@confirm="cancelApplyFun">
			<view class="flex-col col-center tips-dialog" style="padding: 30rpx 0;">
				<image class="icon-lg" src="/static/images/icon_warning.png"></image>
				<view class="m-t-30">是否要撤销申请？</view>
			</view>
		</u-modal>
	</mescroll-uni>
</template>

<script>
	import MescrollMixin from "@/components/mescroll-uni/mescroll-mixins.js";
	import MescrollMoreItemMixin from "@/components/mescroll-uni/mixins/mescroll-more-item.js";
	import {
		getOrderList,
		cancelOrder,
		delOrder,
		confirmOrder,
	} from "@/api/order";
	import {
		getAfterSaleList,
		cancelApply,
	} from "@/api/user";

	export default {
		mixins: [MescrollMixin, MescrollMoreItemMixin],
		data() {
			return {
				orderList: [],
				downOption: {
					auto: false, // 不自动加载 (mixin已处理第一个tab触发downCallback)
				},
				upOption: {
					auto: false, // 不自动加载
					noMoreSize: 4, //如果列表已无数据,可设置列表的总数量要大于半页才显示无更多数据;避免列表数据过少(比如只有一条数据),显示无更多数据会不好看; 默认5
					empty: {
						icon: "/static/images/order_null.png",
						tip: "暂无订单~", // 提示
						fixed: true,
					},
				},
				showCancel: false,
				type: 0,
				orderId: "",
				showLoading: false,
				expressDetaiShow: false,
				showDialog: false
			};
		},
		props: {
			orderType: {
				type: String,
			},
		},
		created() {
			uni.$on("refreshorder", () => {
				this.refresh();
			});

			uni.$on("payment", (params) => {
				setTimeout(() => {
					if (params.result) {
						this.$toast({
							title: "支付成功"
						});
						this.refresh();
					} else {
						this.$toast({
							title: "支付失败"
						});
					}
				}, 500);
			});
		},
		destroyed() {
			uni.$off("payment");
			uni.$off("refreshorder");
		},
		methods: {
			async confirmDialog() {
				const {
					type,
					orderId
				} = this;
				let res = null;
				switch (type) {
					case 0:
						res = await cancelOrder(orderId);
						break;

					case 1:
						res = await delOrder(orderId);
						break;

					case 2:
						res = await confirmOrder(orderId);
						break;
				}

				if (res.code == 1) {
					this.refresh();
					this.$toast({
						title: res.msg,
					});
				}
			},
			dialogOpen() {
				this.$refs.orderDialog.open();
			},
			refresh() {
				this.mescroll.resetUpScroll();
			},
			delOrder(id) {
				this.orderId = id;
				this.type = 1;
				this.$nextTick(() => {
					this.dialogOpen();
				});
			},

			comfirmOrder(id) {
				this.orderId = id;
				this.type = 2;
				this.$nextTick(() => {
					this.dialogOpen();
				});
			},

			cancelOrder(id) {
				this.orderId = id;
				this.type = 0;
				this.$nextTick(() => {
					this.dialogOpen();
				});
			},

			payNow(id) {
				uni.navigateTo({
					url: `/pages/payment/payment?from=${"order"}&order_id=${id}`,
				});
			},
			applyRefund(items, item) {
				const {
					after_sale: {
						able_apply
					},
					order_id
				} = items
				const {
					item_id
				} = item
				if (able_apply != 1) {
					return
				}
				this.$Router.push({
					path: '/bundle/pages/apply_refund/apply_refund',
					query: {
						order_id,
						item_id
					}
				})
			},
			handlegoodCount(item) {
				let count = 0;
				item.order_goods.forEach((i) => {
					count += i.goods_num;
				});
				return count;
			},

			async upCallback(page) {
				let pageNum = page.num; // 页码, 默认从1开始
				let pageSize = page.size; // 页长, 默认每页10条
				let {
					orderType
				} = this;
				if (orderType == 'aftersales') {
					const {
						data,
						code
					} = await getAfterSaleList({
						page_size: pageSize,
						page_no: pageNum,
						type: 'apply'
					})
					if (code == 1) {
						const curPageData = data.list;
						const curPageLen = curPageData.length;
						const hasNext = !!data.more;
						if (page.num == 1) this.orderList = [];
						this.orderList = this.orderList.concat(curPageData);
						this.$set(this.orderList, "pickupCodeShow", false)
						this.mescroll.endSuccess(curPageLen, hasNext);
					}
				} else {
					getOrderList({
						page_size: pageSize,
						page_no: pageNum,
						type: orderType,
					}).then(({
						data
					}) => {
						let curPageData = data.list;
						let curPageLen = curPageData.length;
						let hasNext = !!data.more;
						if (page.num == 1) this.orderList = [];
						this.orderList = this.orderList.concat(curPageData);
						this.$set(this.orderList, "pickupCodeShow", false)
						this.mescroll.endSuccess(curPageLen, hasNext);
					});
				}
			},
			showMapApp(shop) {
				const latitude = shop.latitude
				const longitude = shop.longitude
				// 打开地图导航到该地点
				uni.openLocation({
					latitude: parseFloat(latitude),
					longitude: parseFloat(longitude),
					scale: 15,
					name: shop.name,
					address: shop.shop_address,
					success: res => {
						console.log('打开地图成功:', res)
					},
					fail: res => {
						console.log('打开地图失败:', res)
					},
				})
			},
			codeShowChange(obj) {
				this.$set(obj, "pickupCodeShow", !obj.pickupCodeShow);
			},
			cancelApplyFun() {
				cancelApply({
					id: this.id
				}).then(res => {
					if (res.code == 1) {
						this.$toast({
							title: res.msg
						});
						uni.$emit("refreshorder")
					}
				});
			},
			onShowDialog(id) {
				this.id = id;
				this.showDialog = true
			}
		},
		computed: {
			getOrderStatus() {
				return (status) => {
					let text = "";
					switch (status) {
						case 0:
							text = "待付款";
							break;
						case 1:
							text = "待发货";
							break;
						case 2:
							text = "待收货";
							break;
						case 3:
							text = "已完成";
							break;
						case 4:
							text = "订单已关闭";
							break;
					}
					return text;
				};
			},
			getCancelTime() {
				return (time) => time - Date.now() / 1000;
			},
		},
	};
</script>
<style lang="scss">
	.order-list {
		min-height: calc(100vh - 80rpx);
		padding: 0 20rpx;
		overflow: hidden;

		.order-item {
			border-radius: 10rpx;

			.all-price {
				padding: 20rpx 30rpx;
				justify-content: space-between;
			}
			
			.sale-header {
				padding: 0 20rpx;
			}

			.order-footer {
				height: 100rpx;
				padding: 0 24rpx;

				.plain {
					border: 1px solid #bbbbbb;

					&.red {
						border-color: $-color-primary;
					}
				}

				.btn {
					&.gray-btn {
						border-color: $-color-border;
						color: $-color-muted;
					}
				}
			}

			.express-box,
			.pickup-box {
				margin: 20px 20rpx 0;
				padding: 30rpx;
				background-color: #f6f6f6;
				border-radius: 10rpx;

				.express-info-short,
				.pickup-info {
					display: flex;

					.express-short,
					.pickup-short {
						width: 480rpx;
						flex: 1;
					}

					.express-short {
						overflow: hidden;
						text-overflow: ellipsis;
						white-space: nowrap;
					}
				}

				.express-company {
					margin-top: 20rpx;
					margin-bottom: 10rpx;
					font-size: 26rpx;
				}

				.express-item {
					align-items: flex-start;
					position: relative;
					padding: 10rpx 0;
				}

				.express-left {
					margin-top: 12rpx;
					margin-right: 24rpx;
					height: 100%;
					position: absolute;
					width: 20rpx;
					flex: none;

					.express-icon {
						width: 40rpx;
						height: 40rpx;
					}

					.express-line {
						flex: 1;
						border-left: 2px dotted #E5E5E5;
					}

					.express-doted,
					.express-doted-now {
						width: 16rpx;
						height: 16rpx;
						border-radius: 50%;
					}

					.express-doted {
						background-color: #E5E5E5;
					}

					.express-doted-now {
						background-color: $-color-primary;
					}

				}

				.express-right {
					padding-left: 30rpx;
					line-height: 1.5;

					& .title,
					& .dec {
						margin-bottom: 5rpx;
					}
				}

				.express-item:last-of-type .express-left .express-line {
					border: none;
				}

				.pickup-code {
					margin-top: 10rpx;
					font-size: 28rpx;
					font-weight: 700;
				}

				.text-blue {
					font-size: 26rpx;
					color: #297fdf;
				}
			}
		}
		.sale-content {
			padding: 20rpx 24rpx;
		
			.sale-status {
				padding: 20rpx 40rpx;
				background-color: #F6F6F6;
				border-radius: 6rpx;
			}
		
			.goods-desc {
				min-width: 500rpx;
			}
		}
		
		.sale-footer {
			padding: 0 24rpx 22rpx;
		
			.btn {
				padding: 9rpx 34rpx;
				border: 1px solid $-color-primary;
		
				&.gray-btn {
					border-color: $-color-border;
					color: $-color-muted;
				}
		
				&.black-btn {
					border-color: $-color-border;
					color: $-color-normal;
				}
			}
		}
	}
</style>